package com.lucenly.card.fragment;

import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.lucenly.card.R;
import com.lucenly.card.activity.WebViewActivity;
import com.lucenly.card.adapter.InvitationAAdapter;
import com.lucenly.card.adapter.InvitationBAdapter;
import com.lucenly.card.adapter.Rank_tab_Adapter;
import com.lucenly.card.base.BaseFragment;
import com.lucenly.card.bean.InvitationBean;
import com.lucenly.card.bean.RankBean;
import com.lucenly.card.bean.Rule;
import com.lucenly.card.bean.ShareBean;
import com.lucenly.card.bean.UserInfo;
import com.lucenly.card.constants.Constants;
import com.lucenly.card.constants.UrlDefend;
import com.lucenly.card.event.StringMsgEvent;
import com.lucenly.card.utils.GlideUtils;
import com.lucenly.card.utils.GsonUtil;
import com.lucenly.card.utils.PublicUtil;
import com.lucenly.card.view.MultiImageView;
import com.lucenly.card.view.dialog.NoticeDialog;
import com.lucenly.card.view.dialog.ShareDialog;
import com.lucenly.card.view.refresh2.RefreshLayout;
import com.lucenly.card.view.refresh2.SmartRefreshLayout;
import com.lucenly.card.view.refresh2.listener.OnLoadMoreListener;
import com.lucenly.card.view.refresh2.listener.OnRefreshListener;
import com.siberiadante.toastutils.ToastUtil;
import com.vise.xsnow.dialog.PromptDialog;
import com.vise.xsnow.event.IEvent;
import com.vise.xsnow.event.Subscribe;
import com.vise.xsnow.http.ViseHttp;
import com.vise.xsnow.http.callback.ACallback;
import com.vise.xsnow.utls.SharedPreferencesUtil;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

public class InvitationFragment extends BaseFragment{
    @BindView(R.id.tab_FindFragment_title)
    TabLayout tab_FindFragment_title;
//    @BindView(R.id.vp_FindFragment_pager)
//    WrapContentHeightViewPager vp_FindFragment_pager;
    @BindView(R.id.ll_hd)
    LinearLayout ll_hd;
    @BindView(R.id.tv_share)
    TextView tv_share;
    @BindView(R.id.ll_back)
    LinearLayout ll_back;
    @BindView(R.id.tv_title)
    TextView tv_title;
    @BindView(R.id.smartLayout)
    SmartRefreshLayout smartLayout;
    private List<Fragment> list_fragment;                                //定义要装fragment的列表
    private List<String> list_title;
    Rank_tab_Adapter fAdapter;
    NoticeDialog dialog;
    ShareDialog shareDialog;
//    InvitationAFragment rankAFragment;
//    InvitationBFragment rankBFragment;
    @BindView(R.id.rv_data)
    RecyclerView recyclerView;
    @BindView(R.id.rv_data2)
    RecyclerView recyclerView2;
    @BindView(R.id.ll_yq)
    LinearLayout ll_yq;
    @BindView(R.id.ll_jl)
            LinearLayout ll_jl;
    @BindView(R.id.iv_img)
    MultiImageView iv_img;
    @BindView(R.id.tv_name)
    TextView tv_name;
    @BindView(R.id.tv_gonglue)
    TextView tv_gonglue;
    @BindView(R.id.tv_num)
            TextView tv_num;
    @BindView(R.id.tv_money)
            TextView tv_money;
    @BindView(R.id.scrollView)
    NestedScrollView scrollView;
    InvitationBAdapter adapter2;
    List<InvitationBean> list2 = new ArrayList<>();
    InvitationAAdapter adapter;
    List<RankBean> list = new ArrayList<>();
    int page = 1;
    PromptDialog promptDialog;
    @Override
    protected int getLayoutID() {
        return R.layout.fragment_invitation;
    }

    @Override
    protected void initView(View contentView) {
        tv_title.setText("邀请好友");
        ll_back.setVisibility(View.GONE);
        promptDialog = new PromptDialog(getActivity());
        //将fragment装进列表中
        list_fragment = new ArrayList<>();
//         rankAFragment = new InvitationAFragment();
//         rankBFragment = new InvitationBFragment();
//        list_fragment.add(rankAFragment);
//        list_fragment.add(rankBFragment);
        list_title = new ArrayList<>();
        list_title.add("排行榜");
        list_title.add("我的邀请");
        //为TabLayout添加tab名称
        tab_FindFragment_title.addTab(tab_FindFragment_title.newTab().setText(list_title.get(0)));
        tab_FindFragment_title.addTab(tab_FindFragment_title.newTab().setText(list_title.get(1)));

//        fAdapter = new Rank_tab_Adapter(getChildFragmentManager(),list_fragment,list_title);

        //viewpager加载adapter
//        vp_FindFragment_pager.setAdapter(fAdapter);
        //tab_FindFragment_title.setViewPager(vp_FindFragment_pager);
        //TabLayout加载viewpager
//        tab_FindFragment_title.setupWithViewPager(vp_FindFragment_pager);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        recyclerView.setLayoutManager(layoutManager);
        adapter = new InvitationAAdapter(list);
        adapter.replaceData(list);
        adapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        recyclerView.setAdapter(adapter);

        recyclerView2.setLayoutManager(new LinearLayoutManager(getContext()));
        adapter2 = new InvitationBAdapter();
        adapter2.replaceData(list2);
        adapter2.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        recyclerView2.setAdapter(adapter2);
    }

    @Override
    protected void bindEvent() {
        C(ll_hd);
        C(tv_share);
        C(tv_gonglue);
        smartLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                if(tab_FindFragment_title.getSelectedTabPosition()==0){
//                    rankAFragment.refresh();
                    getData();
                }else{
                    page = 1;
                    getData2();
//                    rankBFragment.refresh();
                }
            }
        });
        smartLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if(tab_FindFragment_title.getSelectedTabPosition()==1){
                    page++;
                    getData2();
                }
            }
        });
        tab_FindFragment_title.addOnTabSelectedListener(new TabLayout.BaseOnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                if(tab.getPosition()==0){
                    smartLayout.setEnableLoadMore(false);
                    ll_yq.setVisibility(View.GONE);
                    ll_jl.setVisibility(View.VISIBLE);
                    getData();
                }else{
                    smartLayout.setEnableLoadMore(true);
                    smartLayout.setNoMoreData(false);
                    ll_yq.setVisibility(View.VISIBLE);
                    ll_jl.setVisibility(View.GONE);
                    getData2();
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }
    @Override
    public boolean isRegisterEvent() {
        return true;
    }
    @Subscribe
    public void refresh(IEvent iEvent){
        if(iEvent!=null&&iEvent instanceof StringMsgEvent){
            if(((StringMsgEvent) iEvent).getMsg().equals("InvitationFragment")){
                smartLayout.finishRefresh();
            }else if(((StringMsgEvent) iEvent).getMsg().equals("tab")){
                scrollView.scrollTo(0,0);
                tab_FindFragment_title.getTabAt(0).select();
            }
        }
    }
    @Override
    protected void initData() {
        PublicUtil.getRule(Constants.RULE_YQ, new ACallback<Rule>() {
            @Override
            public void onSuccess(Rule data) {
                dialog = new NoticeDialog(getActivity(),data,"朕知道了");
            }

            @Override
            public void onFail(int errCode, String errMsg) {

            }
        });
        getData();
        getData2();
        UserInfo user = SharedPreferencesUtil.getInstance().getObject("user", UserInfo.class);
        if(user!=null){
            GlideUtils.getInstance(getActivity()).load(getActivity(),user.getAvatar(),iv_img,R.color.gray_de);
            tv_name.setText(user.getNickname());
        }
    }

    @Override
    protected void lazyLoad() {

    }

    @Override
    protected void processClick(View view) {
        switch (view.getId()){
            case R.id.ll_hd:
                if(dialog==null){
                    getYqMsg();
//                    ToastUtil.showSingletonShort("规则加载失败");
//                    Toast.makeText(getActivity(),"规则加载失败",Toast.LENGTH_SHORT).show();
                }else{
                    dialog.show();
                }
                break;
            case R.id.tv_share:
//                shareDialog.show();
                if(shareDialog==null){
                    PublicUtil.getShareConfig(getActivity(), new PublicUtil.shareInterface() {
                        @Override
                        public void shareSuscess(ShareBean shareBean) {
                            shareDialog = new ShareDialog(getActivity(),shareBean);
                            shareDialog.show();
                        }
                    });
                }else{
                    shareDialog.show();
                }
                break;
            case R.id.tv_gonglue:
                promptDialog.showLoading("正在获取信息....");
                PublicUtil.getConfig(17, new ACallback<Rule>() {
                    @Override
                    public void onSuccess(Rule data) {
                        Intent intent = new Intent(mContext, WebViewActivity.class);
                        intent.putExtra("path",data.value);
                        mContext.startActivity(intent);
                        promptDialog.dismiss();
                    }

                    @Override
                    public void onFail(int errCode, String errMsg) {
                        ToastUtil.showSingletonShort(errMsg);
                        promptDialog.dismiss();
                    }
                });
                break;
        }
    }

    private void getData() {
        ViseHttp.GET(UrlDefend.GET_RANK)
                .addParam("typeId","2")
                .addHeader("Token", SharedPreferencesUtil.getInstance().getString("Token"))
                .request(new ACallback<String>() {
                    @Override
                    public void onSuccess(String data) {
                        smartLayout.finishRefresh();
                        try {
                            JSONObject jsonObject = new JSONObject(data);
                            JSONArray list = jsonObject.getJSONArray("list");
                            if(list!=null){
                                ArrayList<RankBean> rankBeans = GsonUtil.fromJsonList(list.toString(), RankBean.class);
                                adapter.replaceData(rankBeans);
                            }
//                            BusManager.getBus().post(new StringMsgEvent("InvitationFragment"));
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFail(int errCode, String errMsg) {
                        ToastUtil.showSingletonShort(errMsg);
                        smartLayout.finishRefresh();
                        smartLayout.finishLoadMore();
                    }
                });
    }

    private void getData2() {
        ViseHttp.GET(UrlDefend.GET_FREDENS)
                .addHeader("Token", SharedPreferencesUtil.getInstance().getString("Token"))
                .addParam("page",page+"")
                .request(new ACallback<String>() {
                    @Override
                    public void onSuccess(String data) {
                        smartLayout.finishRefresh();
                        smartLayout.finishLoadMore();
                        try {
                            JSONObject jsonObject = new JSONObject(data);
                            tv_money.setText(jsonObject.getDouble("totalInviteFee")+"");
                            tv_num.setText(jsonObject.getInt("totalCount")+"");
                            JSONArray jsonArray = jsonObject.getJSONArray("list");
                            ArrayList<InvitationBean> invitationBeans = GsonUtil.fromJsonList(jsonArray.toString(), InvitationBean.class);
                            if(page==1){
                                adapter2.replaceData(invitationBeans);
                            }else{
                                if(invitationBeans==null||invitationBeans.size()==0){
//                                    Toast.makeText(mContext, "暂无更多数据", Toast.LENGTH_SHORT).show();
                                    ToastUtil.showSingletonShort("暂无更多数据");
                                    smartLayout.finishLoadMoreWithNoMoreData();
                                }else {
                                    adapter2.addData(invitationBeans);
                                }
                            }
//                            BusManager.getBus().post(new StringMsgEvent("InvitationFragment"));

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFail(int errCode, String errMsg) {
                        ToastUtil.showSingletonShort(errMsg);
                        smartLayout.finishRefresh();
                        smartLayout.finishLoadMore();
                    }
                });
    }

    public void getYqMsg(){
        PublicUtil.getRule(Constants.RULE_YQ, new ACallback<Rule>() {
            @Override
            public void onSuccess(Rule data) {
                dialog = new NoticeDialog(getActivity(),data,"朕知道了");
                dialog.show();
            }

            @Override
            public void onFail(int errCode, String errMsg) {
                ToastUtil.showSingletonShort(errMsg);
            }
        });
    }
}
